//
//  AIDiaryReplayBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/3/11.
//
/**
 * 日记回复 - 豆包
 */
import Foundation
import SwiftUI
class AIDiaryReplayBean : Identifiable ,Codable {
    
    var max_tokens: Int64 = configManager.getConfig().AiConfig.maxTokens ?? 1024
    var temperature: Float64 = configManager.getConfig().AiConfig.temperature ?? 0.9
    var top_p: Float64 = configManager.getConfig().AiConfig.top_p ?? 0.95
    var stream = false
    var messages: [MessagesV2]
    var model :String
    
    
    init(model: String?, content : String, botRoleBean: RoleBean, listImage: [String]) {
        self.model = model ?? ""
        let userRoleBean = RoleBean.get(userManager.user, botRoleBean)
        self.messages = AIDiaryReplayBean.getMessagesList(content: content, botRoleBean: botRoleBean, userRoleBean: userRoleBean, listImage: listImage)
    }
    
    private static func getMessagesList(content : String, botRoleBean: RoleBean,
                                        userRoleBean: RoleBean, listImage: [String]) ->[MessagesV2] {
        let time = Date().timeIntervalSince1970
        //动作描述
        let actionDescClose = !AppStorageManager.shared.toggleAiDesc ? "回复只输出最后的话语，不包括任何表情动作" : ""
        let headDesc = configManager.getConfig().getAiDescribe().headDescribe ?? ""
        let botDesc =  RoleBean.getBotDesc(botRoleBean)
        let userDesc =  RoleBean.getUserDesc(botRoleBean)
        let memoryDesc = AppStorageManager.shared.toggleMemoryInject ? configManager.getConfig().getAiDescribe().aiMemoryInjectDesc?.formatAiChatContent(ActiveAIMemoryExt.instance.getAiMemoryStr(botRoleBean: botRoleBean)) ?? "" : ""
        
        let ruleDesc = "\(headDesc)\(configManager.getConfig().getAiDescribe().diaryDescribe ?? "")\(actionDescClose)"
        let enDesc = configManager.getConfig().getAiDescribe().enDesc ?? ""
        let desc = "\(botDesc)\n\n---\n\(userDesc)\(memoryDesc)\(enDesc)"
        
        var listMsg : [MessagesV2] = []
        listMsg.append(MessagesV2("system", botRoleBean.name ?? "", desc.formatAiChat(botRoleBean, time)))
        
        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", "这是我写的日记原文:`\(content)`。"))
        
        var hasImage = false
        if (listImage.isEmpty == false) {
            hasImage = true
            var stringBuffer = ""
            listImage.enumerated().forEach { index, path in
                stringBuffer += "图\(index + 1):\(path)"
            }
            listMsg.append(
                MessagesV2(
                    "user",
                    userRoleBean.name ?? "",
                    "这是我发的图片信息:`\(listImage.map { $0 }.joined(separator: ";"))`。")
            )
        }
        
        let imageMsg = hasImage ? "和我发的图片" : ""
        
        listMsg.append(MessagesV2("user", userRoleBean.name ?? "", "接下来请你结合我写的日记\(imageMsg),\(ruleDesc.formatAiChat(botRoleBean,time))"))
        return listMsg
    }
    
    
}
